/*
 *  Project: EthernetThermometer
 *
 *  Author: brunql
 *  License: WTFPL
 */

.include "tn2313def.inc"
.include "config.h"

; delay 5 to 3000us
; arg 0 = latency in us
; sets to zero R24, R25
.macro wait_us
	ldi		R24,low(F_CPU*@0/4000000)
	ldi		R25,high(F_CPU*@0/4000000)
wait_us_loop:
	sbiw	R25:R24,1
	brne	wait_us_loop
.endm

.macro led_on
	cbi		LED_PORT, LED_BIT
.endm

.macro led_off
	sbi		LED_PORT, LED_BIT
.endm

; code segment
.cseg

; ------------------------------------------------
; interrupt vector table
.org 0
	rjmp	reset

; ------------------------------------------------
; main program start
.org INT_VECTORS_SIZE

; ------------------------------------------------
; reset vector
reset:
	; init stack
	ldi		R16,low(RAMEND)
	out		SPL,R16

	ldi		R16, (1 << LED_BIT)
	out		LED_DDR, R16

	ldi		R16, 0x00
	out		LED_PORT, R16

	; init
	rcall	init_enc

	; init temp sensor
	rcall read_temperature_from_sensor

mainloop:
	; catch packets
	rcall	poll_ip
	rjmp	mainloop

read_temperature_from_sensor:
	led_on
	
	; Reset 1-wire
	rcall	Init_1W
	; Skip address
	ldi		R16, CMD_SKIP_ROM	
	mov		R0, R16
	rcall	Send_1W
	; Read ScratchPad
	ldi		R16, CMD_R_SCRATCHPAD
	mov		R0, R16
	rcall	Send_1W
	; Read bytes
	rcall	ReadBytes_1w
	; Reset 1-wire
	rcall	Init_1W
	; Skip address
	ldi		R16, CMD_SKIP_ROM
	mov		R0, R16
	rcall	Send_1W
	; Convert temperature (start measurement)
	ldi		R16, CMD_CONVERT_T
	mov		R0, R16
	rcall	Send_1W

	led_off
ret

; additional modules
.include "net.h"
.include "enc.h"
.include "enc.inc"
.include "ip.inc"
.include "http.inc"
.include "DS1820.inc"

; ------------------------------------------------
